package org.micro.rbac.util;


import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import org.hibernate.validator.HibernateValidator;
import org.hibernate.validator.HibernateValidatorConfiguration;
import org.micro.rbac.core.exception.BizException;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;


/**
 * @author hongsir
 * @apiNote 摘要:校验单例
 * @since 2019-11-18 12:02
 */
public class ValidUtil {

    public static Validator getValidator() {
        return Validation.byProvider(HibernateValidator.class)
                .configure()
                //开启快速校验--默认校验所有参数，false校验全部
                .failFast(true)
                .addProperty(HibernateValidatorConfiguration.FAIL_FAST, "true")
                .buildValidatorFactory().getValidator();
    }

    public static void valid(Object object, Class<?>... groups) {
        if (object instanceof Collection) {
            List<Object> objectList = Collections.singletonList(object);
            for (int i = 0; i < objectList.size(); i++) {
                validEntity(objectList.get(i), groups);
            }
        } else {
            validEntity(object, groups);
        }
    }

    private static void validEntity(Object object, Class<?>... groups) {
        Set<ConstraintViolation<Object>> constraintViolations = getValidator().validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append(".");
            }
            throw BizException.newError(msg.toString());
        }
    }

}
